<?php

namespace App\Models;


use Auth;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class GroupBuy extends BaseModel
{
    protected $guarded = [];

    protected $appends = ['effectiveDateText', 'isJoin'];

    protected $casts = [
        'member_ids' => 'json'
    ];

    public function list(): HasMany
    {
        return $this->hasMany(GroupBuyData::class, 'group_buy_id');
    }

    public function courseColumn(): BelongsTo
    {
        return $this->belongsTo(CourseColumn::class, 'data_id');
    }

    public function getEffectiveDateTextAttribute(): string
    {
        if ($this->effective_type == 4) return '无';
        // 日期
        if ($this->effective_type == 3) {
            return Carbon::make($this->effective_date)->diffInHours(now()).'小时';
        }
        // 小时
        if ($this->effective_type == 2) {

        }
        // 天数
        if ($this->effective_type == 2) {

        }
    }

    public function getIsJoinAttribute(): bool
    {
        if (Auth::guard('api')->check()) {
            $_memberIds = $this->member_ids ?? [];
            if (in_array(Auth::guard('api')->user()->id, $_memberIds)) return true;
        }

        return false;
    }
}
